/*
 * 创建人：王曙光
 * 创建时间：2011-9-10
 * 功能描述：封装常用功能
 */

/*
 * 增加trim方法
 */
String.prototype.trim = function() {
	return this.replace(/(^\s*)|(\s*$)/g, "");
}
/*
 * 功能说明：过滤重复字符串
 * 使用说明：...abc,def,abc...过滤掉一个abc
 */
String.prototype.Dist = function() {
	var map = {};
	var re = [];
	var array = this.split(",");
	for(var i = 0; i < array.length; i++) {
		if( typeof map[array[i]] == "undefined") {
			map[array[i]] = 1;
			re.push(array[i]);
		}
	}
	return re.join(",");
}
/*
 * 常用功能封装
 */
var Common = function() {
	//是否显示状态栏、目标窗口地址、是否在打开窗体的同时隐藏当前窗体、窗体配置类对象、窗口位置x,y
	function OpenWin(withStatusBar, winPath, hideCurrentWin, winObj, x, y) {
		var options = new air.NativeWindowInitOptions();
		options.minimizable = false;
		options.maximizable = false;
		options.resizable = false;
		options.transparent = true;
		if(!withStatusBar)
			options.type = air.NativeWindowType.LIGHTWEIGHT;
		options.systemChrome = air.NativeWindowSystemChrome.NONE;
		var setting = air.File.applicationDirectory.resolvePath(winPath);

		var bounds = null;
		if(x && y)
			bounds = new air.Rectangle(x, y, winObj._width, winObj._height);
		else
			bounds = new air.Rectangle((air.Capabilities.screenResolutionX - winObj._width) / 2, (air.Capabilities.screenResolutionY - winObj._height ) / 2, winObj._width, winObj._height);
		var win = air.HTMLLoader.createRootWindow(true, options, true, bounds);
		win.load(new air.URLRequest(setting.url));
		if(hideCurrentWin)
			window.nativeWindow.visible = false;
		return win;
	}

	return {
		//检查程序是否是第一次运行
		IsFirstRun : function() {
			var file;
			//获取当前程序版本
			var xmlString = air.NativeApplication.nativeApplication.applicationDescriptor;
			var appXml = new DOMParser();
			var xmlobject = appXml.parseFromString(xmlString, "text/xml");
			var root = xmlobject.getElementsByTagName('application')[0];
			var appId = root.getElementsByTagName("id")[0].firstChild.data;
			var appVersion = root.getElementsByTagName("version")[0].firstChild.data;
			var appName = root.getElementsByTagName("filename")[0].firstChild.data;
			var currentVersion = appVersion;
			file = new air.File(air.File.applicationDirectory.resolvePath("app:/config/version.txt").nativePath);
			if(file.exists) {
				var stream = new air.FileStream();
				stream.open(file, air.FileMode.READ);
				var reversion = stream.readUTFBytes(stream.bytesAvailable);
				stream.close();
				if(reversion != currentVersion) {
					//新版本第一次运行
					return true;
				} else {
					//save file
					var stream = new air.FileStream();
					stream.open(file, air.FileMode.WRITE);
					stream.writeUTFBytes(currentVersion);
					stream.close();
					//不是第一次运行
					return false;
				}
			} else {
				//save file
				var stream = new air.FileStream();
				//alert(file.nativePath)
				stream.open(file, air.FileMode.WRITE);
				stream.writeUTFBytes(currentVersion);
				stream.close();
				//first run
				return true;
			}
		},
		//Air拖拽封装
		DragStart : function(obj) {
			$(obj).bind("mousedown", function(event) {
				if(Const._isdrag)
					window.nativeWindow.startMove();
			});
		},
		//通过title获取窗体对象
		GetWin : function(title) {
			var loginWindow = air.NativeApplication.nativeApplication.openedWindows;
			for(var i = 0; i < loginWindow.length; i++) {
				if(loginWindow[i].title === title) {
					return loginWindow[i];
				}
			}
			return null;
		},
		//初始化配置对象为空
		GetEmptyConfig : function() {
			var Config = {};
			//WebService地址
			Config.WsURL = "";
			//登录用户名
			Config.LoginCode = "";
			//登录密码
			Config.Password = "";
			//记录窗口当前位置X坐标
			Config.WinStartX = "";
			//记录窗口当前位置Y坐标
			Config.WinStartY = "";
			//记录窗口宽度
			Config.WinWidth = "";
			//记录窗口高度
			Config.WinHeight = "";
			//是否自动登录
			Config.AutoLogin = "";
			//是否记录登录密码
			Config.RembPwd = "";
			//点击关闭按钮时是否关闭窗口
			Config.Close = "";
			//来寻呼时是否播放声音
			Config.PlaySound = "";
			//来寻呼时是否弹窗提示
			Config.Pop = "";
			//临时记录两次查看未阅寻呼之间的差值，防止重复提醒
			Config.CallNum = "";
			//寻呼发送时快捷键Enter or Ctrl+Enter
			Config.MsgConfirm = "";
			return Config;
		},
		//系统弹框提示
		ShowTips : function(tips) {
			var show = "<div class='tipmark' >";
			show += "<div class='tipmsg'>";
			show += "<div class='close tipclose'></div>";
			show += "<div class='tipimg'></div>";
			show += "<div class='tiptext'>" + tips + "</div>";
			show += "<input type='button' value='确定' class='subbtn tipbtn'></div>";
			show += "</div>";
			show += "</div>";
			//页面中已经存在隐藏的弹出窗
			if($(".tipmark").length > 0) {
				$(".tiptext").html(tips);
				$(".tipmark").show();
				//确定弹框位置
				var top = window.nativeWindow.height / 2 - 40;
				var left = window.nativeWindow.width / 2 - 100;
				$(".tipmsg").css({
					"top" : top + "px",
					"left" : left + "px"
				});
				$(".tipmsg").show();

			} else {
				//全新弹框
				$(document.body).append(show);
				//确定弹框位置
				var top = window.nativeWindow.height / 2 - 40;
				var left = window.nativeWindow.width / 2 - 100;
				$(".tipmsg").css({
					"top" : top + "px",
					"left" : left + "px"
				});
			}
			//隐藏弹框
			$(".tipclose,.tipbtn").live("click", function() {
				$(".tipmark").hide();
				$(".tipmsg").hide();
			});
		},
		//获取当前机器的屏幕
		GetCurrentScreen : function() {
			var current;
			var screens = air.Screen.getScreensForRectangle(window.nativeWindow.bounds);
			(screens.length > 0) ? current = screens[0] : current = air.Screen.mainScreen;
			return current;
		},
		//截取字符串，中文按双字节处理
		CheckLength : function(str, length) {
			var index = 0;
			var len = 0;
			for(var i = 0; i < str.length; i++) {
				if(len - 1 >= length)
					return str.substring(0, index - 1);
				if(len >= length)
					return str.substring(0, index);
				if(str.charCodeAt(i) > 255)
					len += 2;
				else
					len++;
				index++;
			}
			return str;
		},
		//截取时间或者日期  smalldate,smalltime
		GetTime : function(type) {
			var date = new Date();
			var year = date.getYear();
			var month = date.getMonth();
			if(month.length == 1) {
				month = "0" + month;
			}
			var day = date.getDay();
			if(day.length == 1) {
				day = "0" + day;
			}
			var hour = date.getHours();
			if(hour.length == 1) {
				hour = "0" + hour;
			}
			var minute = date.getMinutes();
			if(minute.length == 1) {
				minute = "0" + minute;
			}
			switch(type) {
				case "smalldate":
					return month + "-" + day
				case "smalltime":
					return hour + ":" + minute;
			}
		},
		//打开配置页面
		OpenSetWin : function() {
			OpenWin(true, 'setting.html', false, Const.setting);
		},
		//寻呼发送页面
		OpenMsgWin : function() {
			//检查并关闭已经打开的窗口
			var rwin = Common.GetWin("回复寻呼");
			if(rwin) {
				rwin.close();
			}
			var win = OpenWin(true, 'msg.html', false, Const.msg);
			//传递数据
			App.setTempData(Const.msg._targetid);
			//设置窗口的最小大小
			win.window.nativeWindow.minSize = new air.Point(Const.msg._minsizex, Const.msg._minsizey);
		},
		//文件下载页面
		OpenDownloadWin : function() {
			var win = OpenWin(false, 'filedownload.html', true, Const.download);
			//传递数据
			win.window.returnValue = Const.download._fileId + "$#$" + Const.download._filePath;
		},
		//登录页面
		OpenLoginWin : function() {			
			var win = OpenWin(true, 'login.html', false, Const.login);
			Const.login._leave = true;
			win.window.returnValue = "1";
			win = null;			
			window.nativeWindow.close();
		},
		//寻呼弹框
		PopWin : function(x, y) {
			//关闭已打开窗口
			var pop = Common.GetWin("popmsg");
			if(pop)
				pop.close();
			var win = OpenWin(false, 'pop.html', false, Const.pop, x, y);
			win.window.returnValue = Const.pop._msgid + "$#$" + Const.pop._from + "$#$" + Const.pop._msg;
		},
		//人员选择控件
		OpenUserList : function() {
			var win = OpenWin(false, 'org.html', true, Const.userlist);
			win.window.returnValue = Const.userlist._idlist;
		},
		//日记详情
		OpenDiaryDetail : function(x, y) {
			//关闭已打开窗口
			var diaryWin = Common.GetWin("diarydetail")
			if(diaryWin)
				diaryWin.close();
			var win = OpenWin(false, 'diary.html', false, Const.diarydetail, x, y);
		},
		//写日记
		OpenDiaryNew : function() {
			var win = OpenWin(true, 'newdiary.html', false, Const.diarynew);
		},
		//名片卡
		OpenNameCard : function(x, y) {
			var cardWin = Common.GetWin("namecard");
			if(cardWin)
				cardWin.close();
			var win = OpenWin(false, 'namecard.html', false, Const.namecard, x, y);
			return win.window.nativeWindow;
		},
		//菜单窗口
		OpenMenu : function(x, y) {
			var menuWin = Common.GetWin("menu");
			if(menuWin) {
				menuWin.x = x;
				menuWin.y = y;
				menuWin.activate();
			} else {
				var win = OpenWin(false, 'menu.html', false, Const.menu, x, y);
				win.window.returnValue = Const.main._cheight.toString() + "$#$" + Const.main._msgcount.toString();
			}
		}
	}
}();
